# -*- coding: utf-8 -*-
# @Time    : 2021/4/20 16:25
# @Author  : JoSuper
# @File    : access_course.py
# @Software: PyCharm
# @Date    : 2021/4/20
import time
from urllib.parse import urlparse

from bs4 import BeautifulSoup

from config import Config


class ViewCourse():

    def __init__(self, config=None):
        self.config = config or Config

    def access_course(self, course_id):
        course_index_url = f"https://cs.xnjd.cn/course/Course_video.action?courseId={course_id}"
        resp = self.config.session.get(course_index_url)
        soup = BeautifulSoup(resp.text, "html.parser")
        a_attrs = soup.find_all("a", attrs={"target": "_blank"})
        course_info_url = "https://cs.xnjd.cn/course/"
        for a_tag in a_attrs:
            if a_tag.text.strip() != "查看":
                continue
            href = a_tag.get("href", "")
            if href == "":
                continue
            course_url = course_info_url + href
            headers = {}
            if href.startswith("http") and "/player/player.html" in href:
                headers["Referer"] = course_index_url
                url_parse_result = urlparse(href)
                query = url_parse_result.query
                query_list = query.split("&")
                mark_url = f"http://cs.xnjd.cn/course/Course_newVideo.action?courseId={course_id}&id={query_list[4]}"
                resp = self.config.session.post(mark_url, headers=headers)
            else:
                resp = self.config.session.get(course_url, headers=headers, allow_redirects=True)
            if resp.status_code == 200:
                print(course_url, " access!")

    def run(self):
        # all_course_url = "https://study.xnjd.cn/study/CourseRelation_studentViewAllCourse.action"
        all_course_url = "https://study.xnjd.cn/study/CourseRelation_studentViewCurrentTermCourse.action"
        resp = self.config.session.get(all_course_url)
        soup = BeautifulSoup(resp.text, "html.parser")
        table = soup.find("table", attrs={"class": "bluetable"})
        # a_list = table.find_all("a", attrs={"target": "_blank"})
        a_list = table.find_all("a", text="进入课程")
        for a_tag in a_list:
            if a_tag.text.strip() != "进入课程":
                continue
            href = a_tag.get("href", "")
            if href == "":
                continue
            course_id = href.split("=")[-1]
            # if self.config.last_year_course_id != "" and course_id == self.config.last_year_course_id:
            #     break
            self.access_course(course_id)
